// $(function () {
/**
 * Created by 烈日影视 on 2017/12/9.
 */


const belong_model_person = 100;

// const nav_person = 1;

var isMobile = ismobile();

var addressAndTime;

function WebViewDidFinishLoad() {

    var message = {

        "VcWay": "SendId"
    };

    window.webkit.messageHandlers.CallTerMinalModel.postMessage(message);
}
document.onreadystatechange = function () {

    if (document.readyState == "complete") {

        if (isMobile == 0) {

            window.android.getAndroidId("pp")
        }
    }

};


//getNav(belong_model_person);

function receiveiOSDateAndAddressData(i) {//地址加时间 ios

    addressAndTime = $.parseJSON(i);

    //addressAndTime.addr = addressAndTime.secondAddress;

    addressAndTime.addressID = addressAndTime.districtId;

    addressAndTime.startsDate = timeFormat(addressAndTime.startsDate);

    addressAndTime.endDate = timeFormat(addressAndTime.endDate);

    getNav(belong_model_person);
}

function receive_android_device_location_search(k) {//地址加时间 安卓

    addressAndTime = $.parseJSON(k);

    //addressAndTime.addr = addressAndTime.addr;

    addressAndTime.addressID = addressAndTime.districtId;

    addressAndTime.startsDate = timeFormat(addressAndTime.startsDate);

    addressAndTime.endDate = timeFormat(addressAndTime.endDate);
    
    getNav(belong_model_person);
}



function Params(page, size, cat_id, belong_model, price_start, price_end, hot_sort, price_sort, address, cat_level, start_time, end_time, url, keywords, goods_sn) {
    this.page = page;

    this.size = size;

    this.cat_id = cat_id;

    this.belong_model = belong_model;

    this.price_start = price_start;

    this.price_end = price_end;

    this.hot_sort = hot_sort;

    this.price_sort = price_sort;

    this.address_id = address;

    this.start_time = start_time;

    this.end_time = end_time;

    this.url = url;

    this.keywords = keywords;

    this.cat_level = cat_level;

    this.goods_sn = goods_sn;
}

var curNavIndex = 0;

var mescrollArr = null;

var paramsArr = null;

//动态加载人力导航栏
function getNav(id) {

    $.ajax({

        type: "POST",

        url: url + "users/navigationbar",

        dataType: "json",

        //async: "false",

        data: {

            belong_model: id
        },

        success: function (data) {

            // alert(JSON.stringify(data))

            //console.log(data)

            var html1 = template("navlistTpl", data);

            $("header #ul").html(html1);

            var html2 = template("productListTpl", {data: data.data.list});

            $("#content").html(html2);

            curNavIndex = 0;

            mescrollArr = new Array(data.data.list.length + 1);

            mescrollArr[0] = initMescroll("mescroll0", "dataList0");

            paramsArr = new Array(data.data.list.length + 1);

            paramsArr[0] = initParams(0);

            navClick();
            //
            //var _liwidth = $('#0').width();

            //var _ullength = $("#ul li").length;

            //var _ulwidth = _liwidth * _ullength;

            //$("#ul").width(_ulwidth);

        }
    })
}

function initParams(cat_id) {
    
    //console.log(addressAndTime)

    var params = new Params(1, 10, cat_id, belong_model_person);

    params.cat_level = 100;

    params.hot_sort = null;

    params.price_sort = null;

    params.price_start = null;

    params.price_end = null;

    params.address_id = addressAndTime.addressID;

    params.start_time = addressAndTime.startsDate;

    params.end_time = addressAndTime.endDate;

    params.url = "product/goods/webList";
    
    //console.log(params)

    return params;
}
//点击导航栏刷新列表
function navClick() {

    $("#ul").on("click", "li", function () {

        var index = Number($(this).data("index"));

        if (curNavIndex != index) {

            //更改列表条件

            $("header ul li a.active").removeClass("active");

            $(this).addClass("active");

            //隐藏当前列表和回到顶部按钮

            $("#mescroll" + curNavIndex).hide().addClass("hide");

            mescrollArr[curNavIndex].hideTopBtn();

            //显示对应的列表

            $("#mescroll" + index).show().removeClass("hide");

            //取出菜单所对应的mescroll对象,如果未初始化则初始化

            if (paramsArr[index] == null || mescrollArr[index] == null) {

                paramsArr[index] = initParams($(this).attr("id"));

                mescrollArr[index] = initMescroll("mescroll" + index, "dataList" + index);

            } else {

                //检查是否需要显示回到到顶按钮

                var curMescroll = mescrollArr[index];

                var curScrollTop = curMescroll.getScrollTop();

                if (curScrollTop >= curMescroll.optUp.toTop.offset) {

                    curMescroll.showTopBtn();

                } else {

                    curMescroll.hideTopBtn();
                }
            }

            resetFilter($(this), curNavIndex);

            //更新标记

            curNavIndex = index;
        }
    });
}
//重置筛选条件
function resetFilter(that, oldIndex) {

    that.parents("header").siblings("div.sort").find(".sortWay p").html("排序方式").removeClass("sortColor").siblings("b").removeClass("sortBackImg1");

    that.parents("header").siblings("div.sort").find(".priceRange p").html("价格区间").removeClass("sortColor").siblings("b").removeClass("sortBackImg1");

    that.parents("header").siblings("div.sort").find(".sdrop_down li").removeClass("sortColor").find(".ok").addClass("hide");

    that.parents("header").siblings("div.sort").find(".pdrop_down li").removeClass("sortColor").find(".ok").addClass("hide");

    var params = paramsArr[oldIndex];

    params.hot_sort = 0;

    params.price_sort = 0;

    params.price_start = 0;

    params.price_end = 0;
}
//点击排序方式刷新列表
$(".sdrop_down").on("click", "li", function () {

    var sort_id = $(this).attr("id");

    var params = paramsArr[curNavIndex];

    switch (sort_id) {

        case "hot":

            params.hot_sort = 100;

            params.price_sort = 0;

            break;

        case "low_price":

            params.hot_sort = 0;

            params.price_sort = 100;

            break;

        case "high_price":

            params.price_sort = 200;

            params.hot_sort = 0;

            break;
    }
    var mescroll = mescrollArr[curNavIndex];

    mescroll.resetUpScroll();

});
//点击价格区间刷新列表
$(".pdrop_down").on("click", "li", function () {

    var price_id = $(this).attr("id");

    var params = paramsArr[curNavIndex];

    switch (price_id) {

        case "l_price":

            params.price_start = 1000;

            params.price_end = 5000;

            break;

        case "h_price":

            params.price_start = 5001;

            params.price_end = 10000;

            break;

        case "normal":

            params.price_start = 0;

            params.price_end = 0;

            break;
    }
    ;
    var mescroll = mescrollArr[curNavIndex];

    mescroll.resetUpScroll();
});
//上拉刷新，下拉加载
function initMescroll(mescrollId, clearEmptyId) {

    var mescroll = new MeScroll(mescrollId, { //第一个参数"mescroll"对应上面布局结构div的id

        up: {
            callback: upCallback, //上拉加载的回调

            noMoreSize: 5,

            isBounce: false,

            clearEmptyId: clearEmptyId,

            empty: {

                icon: "./img/wallet_img_no@3x.png", //图标,默认null

                tip: "暂无相关数据~  再逛逛~", //提示
                //btntext: "去逛逛 >", //按钮,默认""
                //btnClick: function () {//点击按钮的回调,默认null
                //    var all = $(".mescroll-empty .empty-btn").parents("div#content").siblings("div#header").children("header").find("li").eq(0);
                //    all.click();
                //    all.find("a").addClass("active");
                //    // alert("点击了按钮,具体逻辑自行实现");
                //    $(".mescroll-totop ").css("display", "none");
                //}
            },
        }
    });
    return mescroll;
}
//上拉加载的回调
function upCallback(page) {

    var dataIndex = curNavIndex; //记录当前联网的nav下标,防止快速切换时,联网回来curNavIndex已经改变的情况;

    var params = paramsArr[dataIndex];

    params.page = page.num;

    params.size = page.size;
    
    //console.log(params)

    getListDataFromNet(dataIndex, params, function (data) {

        //必传参数(当前页的数据个数, 总数据量)

        if (data.codes == 200) {

            var listData = data.data.list;

            mescrollArr[dataIndex].endBySize(listData.length, data.totalCount);

            //console.log(data)

            listData.forEach(function (item) {

                if (item.goods_tag) {

                    if (item.goods_tag.length > 3) {

                        item.goods_tag.length = 3;
                    }
                }
            });
            setListData(data, dataIndex);
        } else {

            mescrollArr[dataIndex].endBySize(0, 0);

            mescrollArr[dataIndex].showEmpty();
        }
    }, function () {
        //联网失败的回调,隐藏下拉刷新和上拉加载的状态;
        mescrollArr[dataIndex].endErr();
    });

}

function setListData(data, dataIndex) {

    var dataList = "dataList" + dataIndex;

    var html = template("personlistTpl", data);

    $("#" + dataList).append(html);

}
//从服务器获取数据
function getListDataFromNet(dataIndex, params, successCallback, errorCallback) {

    $.ajax({

        url: url + 'users/fourModel',

        type: "POST",

        dataType: "json",

        //async: "false",

        data: params,

        success: function (data) {

            successCallback(data);
        },

        error: errorCallback
    });
}
//搜索关键词 拿到搜索关键词 调用接口  点击排序方式和价格区间刷新列表
function receive_android_search(k) {

    // alert(k);

    var keywords = k;

    var params = paramsArr[curNavIndex];

    params.keywords = keywords;

    var mescroll = mescrollArr[curNavIndex];

    mescroll.resetUpScroll();

    // search(keywords, 200);
}

function receiveiOSSearchData(i) {//搜索关键词 ios

    // alert(JSON.stringify(i));

    var keywords = i.searchData;

    var params = paramsArr[curNavIndex];

    params.keywords = keywords;

    var mescroll = mescrollArr[curNavIndex];

    mescroll.resetUpScroll();

    // search(keywords, Number(200));
}
//格式化时间
function timeFormat(time) {//2017-12-27 12:00

    var y = time.substring(0, 4);

    var m = time.substring(5, 7);

    var d = time.substring(8, 10);

    var h = time.substring(11, 13);

    var s = time.substring(14, 16);

    // return(s)

    return (y + m + d + h + s);
}

//点击其中某一项产品进入商品详情
var isRun = true;

$("#content").on("click", "li", function () {

    if (isRun) {

        var li_id = $(this).attr("id");

        if(!li_id) return false;

        var json = {

            "goods_id": Number(li_id),

            "startDate": addressAndTime.startsDate,

            "endDate": addressAndTime.endDate,

            "addressID": addressAndTime.addressID

        };

        if (isMobile == 1) {

            var message = {

                "VcData": json,

                "VcName": "TerminalDetails",

                "VcWay": "PushVCName"
            };

            window.webkit.messageHandlers.CallTerMinalModel.postMessage(message);

            //CallTerMinalModel.jsCalliOSWithPushVCName({
            //
            //    "VcData": json, "VcName": "TerminalDetails"
            //
            //});

        } else if (isMobile == 0) {


            window.android.jumpToProjectDetal(JSON.stringify(json));

        }

        isRun = false;

    }

    setTimeout(function () {

        isRun = true;

    }, 1500);//点击后相隔多长时间可执行


});


$("#header .category").on("click", function () {

    //alert("ok");

    if (isMobile == 1) {

        window.webkit.messageHandlers.CallTerMinalModel.postMessage({"VcWay": "PushClassifyPopView"});

        //CallTerMinalModel.jsCalliOSWithPushClassifyPopView()

    } else if (isMobile == 0) {

        window.android.openDeviceFilterClassfyDrawer("ok")
    }
});

function ismobile() {
    //判断访问终端
    var browser = {
        versions: function () {
            var u = navigator.userAgent, app = navigator.appVersion;
            return {
                trident: u.indexOf('Trident') > -1, //IE内核
                presto: u.indexOf('Presto') > -1, //opera内核
                webKit: u.indexOf('AppleWebKit') > -1, //苹果、谷歌内核
                gecko: u.indexOf('Gecko') > -1 && u.indexOf('KHTML') == -1,//火狐内核
                mobile: !!u.match(/AppleWebKit.*Mobile.*/), //是否为移动终端
                ios: !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), //ios终端
                android: u.indexOf('Android') > -1 || u.indexOf('Adr') > -1, //android终端
                iPhone: u.indexOf('iPhone') > -1, //是否为iPhone或者QQHD浏览器
                iPad: u.indexOf('iPad') > -1, //是否iPad
                webApp: u.indexOf('Safari') == -1, //是否web应该程序，没有头部与底部
                weixin: u.indexOf('MicroMessenger') > -1, //是否微信 （2015-01-22新增）
                qq: u.match(/\sQQ/i) == " qq" //是否QQ
            };
        }(),
        language: (navigator.browserLanguage || navigator.language).toLowerCase()
    };

    if (browser.versions.mobile == true) {
        if (browser.versions.iPhone == true) {
            return '1';
        } else if (browser.versions.android == true) {
            return '0';
        }
    } else {

    }
}